<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="self-folder-container">
    <div class="address-bar">
      <div class="path-breadcrumb">
        <div 
          v-for="(item, index) in currentPath" 
          :key="item.id" 
          class="path-item"
          @click="navigateTo(index)"
        >
          <i v-if="index === 0" class="fas fa-hard-drive"></i>
          <span>{{ item?.data }}</span>
          <span v-if="index < currentPath.length - 1" class="path-divider">/</span>
        </div>
      </div>
      
      <el-input 
        class="search-box" 
        size="small"
        placeholder="关键字查询" 
        v-model="searchQuery"
      >
        <template #append>
          <el-button @click="searchTreeData" :icon="Search" />
        </template>
      </el-input>
      <!-- <el-input
        v-model="input3"
        style="max-width: 600px"
        placeholder="Please input"
        class="input-with-select"
      >
        <template #append>
          <el-button :icon="Search" />
        </template>
      </el-input> -->
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content" v-loading="loading">
      <!-- 右侧文件区域 -->
      <div class="content-area">
        <div v-if="operatorType == 'ADD' || operatorType == 'EDIT'" class="toolbar">
          <div class="toolbar-title">
            <i class="fas fa-folder-open"></i>
            {{ currentFolder?.data }}
          </div>
          <div class="file-actions">
            <el-button type="primary" size="small" @click="saveFile">
              <i class="fas fa-file-circle-plus"></i>
              保存数据
            </el-button>
          </div>
        </div>
        <div class="file-grid" v-if="currentFolder && currentFolder.content">
          <!-- 上级目录 -->
          <div 
            v-if="currentPath.length > 0"
            class="file-item" 
            @click="goUp"
          >
            <div class="file-name">...</div>
          </div>
          <!-- 文件夹 -->
          <div 
            class="file-item" 
            v-for="folder in currentFolder.content" 
            :key="folder.detail.objectId"
            @click="selectFolder(folder)"
            @contextmenu.prevent="showContextMenu($event, folder, 'folder')"
          >
            <div class="file-name"><img :src="model" alt="" style="height: 16px; width: 16px" />{{ folder.data }}</div>
          </div>
        </div>
        <div class="tree-pagination">
            <pagination
              v-show="total > 30"
              style="margin-top: 0;height: 38px;"
              v-model:page="pageNum"
              v-model:limit="pageSize"
              :total="total"
              :background="false"
              layout="prev, pager, next, jumper"
              @pagination="queryCurrentPageData"
            />
          </div>
      </div>
    </div>
  </div>
  
  <!-- 上下文菜单 -->
  <div 
    class="context-menu" 
    v-if="contextMenu.visible" 
    :style="{ top: contextMenu.y + 'px', left: contextMenu.x + 'px' }"
  >
    <div v-if="!hasChildren" class="menu-item" @click="treeNodeOperate('ADD')">
      <CopyDocument style="width: 1em; height: 1em; margin-right: 8px"/>
      <span>复制</span>
    </div>
    <div class="menu-item" @click="treeNodeOperate('EDIT')">
      <Edit style="width: 1em; height: 1em; margin-right: 8px"/>
      <span>编辑</span>
    </div>
    <div class="menu-item" @click="treeNodeOperate('DELETE')">
      <Delete style="width: 1em; height: 1em; margin-right: 8px"/>
      <span style="color: #f96868;">删除</span>
    </div>
  </div>
</template>

<script setup name="Dept">
import model from '@/assets/images/modelEstablish/model.svg';
import { Search } from '@element-plus/icons-vue'
import {
  getAssetDataList
} from '@/api/material/index.ts';
const props = defineProps(['modelId', 'treeResult', 'notInitRequest']);
const emit = defineEmits(['getTreeNodeDetail', 'saveData']);
//目录结构
const detailTreeData = ref([]);
const dataAssetType = ref('');
const assetTableData = ref([]);
const total = ref(0);
const hasChildren = ref(true);
const operatorType = ref('');     
// 当前路径
const currentPath = ref([])
const currentFolder = ref([])
const loading = ref(false);
// 当前文件夹
// const currentFolder = computed(() => {
//   return currentPath.value[currentPath.value.length - 1]
// })
const firstLevelPageNum = ref(1); 
const pageNum = computed(() => {
  return currentPath.value[currentPath.value.length - 1]?.detail?.pageNum || firstLevelPageNum.value || 1
})
const pageSize = ref(30);
// const pageSize = computed(() => {
//   return currentPath.value[currentPath.value.length - 1].detail.pageSize
// })

// 搜索查询
const searchQuery = ref('')

// 上下文菜单
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  type: null,
  item: null
})
const searchTreeData = (val) => {
  if (val) {
    currentPath.value[currentPath.value.length - 1].detail.pageNum = 1;
    searchSubFolder(currentPath.value[currentPath.value.length - 1], 'navigateTo')
  }
}
const queryCurrentPageData = (val) => {
  if (currentPath.value.length > 0) {
    currentPath.value[currentPath.value.length - 1].detail.pageNum = val.page;
    searchSubFolder(currentPath.value[currentPath.value.length - 1], 'navigateTo')
  } else {
    firstLevelPageNum.value = val.page;
    initTreeData(val.page)
  }
  
}
// 导航到指定文件夹
const selectFolder = (folder) => {
   operatorType.value = 'VIEW'
  searchSubFolder(folder)
  emit('getTreeNodeDetail', {
    type: 'VIEW',
    data: folder.detail,
    name: folder.data
  })
}

const treeNodeOperate = (type) => {
  operatorType.value = type;
  emit('getTreeNodeDetail', {
    type,
    data: contextMenu.value.item.detail,
    name: contextMenu.value.item.data
  })
}

const refreshCurrent = () => {
  let current = currentPath.value[currentPath.value.length - 1];
  searchSubFolder(current, 'navigateTo')
}

// 查询子目录
const searchSubFolder = (row, type = 'toNew') => {
  const detail = row.detail;
  if (!hasChildren.value && type == 'toNew') {
    return;
  }
  loading.value = true;
  getAssetDataList({
    "modelId" : '',
    "tableName" : detail?.childTables && detail.childTables.length > 0 ? detail.childTables[0] : '',
    "parentId" : detail?.objectId,
    "importRecordIds" : [""],
    "pageNum" : type == 'toNew' ? 1 : pageNum.value,
    "pageSize" : 30,
    "keyword" : searchQuery.value
  }).then(res => {
    if (res?.data?.treeResult?.content?.length > 0) {
      if (res.data.showType == 'tree') {
        hasChildren.value = res.data.treeResult.hasChildren;
        detailTreeData.value = res.data?.treeResult.content;
        total.value = res.data?.treeResult?.totalSize || 0;
        // 缓存没一层级信息
        currentFolder.value = res.data?.treeResult;
        // 
        type !== 'navigateTo' && (
          row.detail.pageNum = 1,
          currentPath.value.push(row)
        )
        contextMenu.value.visible = false
      }
      loading.value = false;
    } else {
      return;
    }
  }).finally(() => {
    loading.value = false;
  })
}

// 导航到指定路径索引
const navigateTo = (index) => {
  operatorType.value = 'VIEW'
  currentPath.value = currentPath.value.slice(0, index + 1)
  contextMenu.value.visible = false
  searchSubFolder(currentPath.value[currentPath.value.length - 1], 'navigateTo')
}

// 返回上级目录
const goUp = () => {
  // if (currentPath.value.length > 1) {
  currentPath.value.pop()
  if (currentPath.value.length == 0) {
    initTreeData();
  } else {
    searchSubFolder(currentPath.value[currentPath.value.length - 1], 'navigateTo')
  }
  contextMenu.value.visible = false
  
}

// 显示上下文菜单
const showContextMenu = (event, item, type) => {
  contextMenu.value = {
    visible: true,
    x: event.pageX - 250,
    y: event.pageY - 150,
    type,
    item
  }
}

// 隐藏上下文菜单
const hideContextMenu = () => {
  contextMenu.value.visible = false
}

// 删除项目
const deleteItem = () => {
  if (contextMenu.value.item) {
    // 实际应用中应调用API删除
    ElMessageBox.confirm(`确定要删除 "${contextMenu.value.item.name}" 吗？`, '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      ElMessage.success(`"${contextMenu.value.item.name}" 已删除`);
      contextMenu.value.visible = false;
    }).catch(() => {});
  }
}

// 新建文件夹
const newFolder = () => {
  const folderName = prompt('请输入文件夹名称:', '新建文件夹')
  if (folderName) {
    // 实际应用中应调用API创建
    ElMessage.success(`文件夹 "${folderName}" 已创建`);
  }
}

// 新建文件
const newFile = () => {
  const fileName = prompt('请输入文件名称:', '新建文件.txt')
  if (fileName) {
    // 实际应用中应调用API创建
    ElMessage.success(`文件 "${fileName}" 已创建`);
  }
}

// 保存数据
const saveFile = () => {
  console.log('treeNodeOperate', contextMenu.value.item)
  emit('saveData', {
    type: 'SAVE',
    data: contextMenu.value.item.detail,
    name: contextMenu.value.item.data
  })
}

const initTreeData = (page = 1) => {
  getAssetDataList({
    modelId: props.modelId,
    pageNum: page,
    pageSize: 30
  }).then(res => {
    dataAssetType.value = res.data.showType;
    if (res.data.showType == 'tree') {
      hasChildren.value = res.data.treeResult.hasChildren;
      detailTreeData.value = res.data?.treeResult.content;
      total.value = res.data?.treeResult?.totalSize || 0;
      // 缓存没一层级信息
      currentFolder.value = res.data?.treeResult;
    } else if (res.data.showType == 'table') {
      assetTableData.value = res.data?.tableResult?.contentData || [];
      total.value = res.data?.tableResult?.totalSize || 0;
    }
  }).finally(() => {
    
  })
}

// 点击页面其他位置隐藏上下文菜单
document.addEventListener('click', hideContextMenu)
onMounted(() => {
  if (props?.notInitRequest) {
    hasChildren.value = props?.treeResult.hasChildren;
    detailTreeData.value = props?.treeResult.content;
    total.value = props?.treeResult?.totalSize || 0;
    // 缓存没一层级信息
    currentFolder.value = props?.treeResult;
  } else {
    initTreeData();
  }
})
defineExpose({
  refreshCurrent
})
</script>
<style scoped>
.self-folder-container {
  position: relative;
  width: 100%;
  /* max-width: 500px; */
  background: white;
  border-radius: 12px;
  /* box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); */
  overflow: hidden;
  display: flex;
  flex-direction: column;
  /* height: 90vh; */
} 

/* 地址栏样式 */
.address-bar {
  background: #f0f5ff;
  padding: 12px 25px;
  display: flex;
  align-items: center;
  gap: 15px;
  border-bottom: 1px solid #dce1e8;
}

.nav-buttons {
  display: flex;
  gap: 8px;
}

.nav-btn {
  width: 32px;
  height: 32px;
  background: white;
  border: 1px solid #dce1e8;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.nav-btn:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.path-breadcrumb {
  flex: 1;
  background: white;
  border: 1px solid #dce1e8;
  border-radius: 4px;
  /* padding: 8px 15px; */
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  min-height: 32px;
  /* line-height: 32px; */
  gap: 5px;
}

.path-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  /* padding: 4px 0px; */
  border-radius: 4px;
  transition: all 0.2s;
}

.path-item:hover {
  background: #e6f7ff;
}

.path-item i {
  margin-right: 5px;
}

.path-divider {
  color: #999;
  margin: 0 5px;
}

.search-box {
  width: 130px;
}

/* 主内容区样式 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: #f8fafd;
  border-right: 1px solid #dce1e8;
  padding: 15px 0;
  overflow-y: auto;
}

.sidebar-title {
  padding: 10px 25px;
  font-weight: 600;
  color: #2a5298;
  display: flex;
  align-items: center;
  gap: 10px;
}

.directory-tree {
  padding: 5px 15px;
}

.tree-node {
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: all 0.2s;
}

.tree-node:hover {
  background: #e6f7ff;
}

.tree-node.active {
  background: #d0e8ff;
  font-weight: 500;
}

.tree-children {
  padding-left: 24px;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.toolbar {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dce1e8;
}

.toolbar-title {
  font-size: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.file-grid {
  flex: 1;
  padding: 20px;
  /* display: grid; */
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 25px;
  overflow-y: auto;
}

.file-item {
  /* line-height: 25px;
  height: 25px; */
  margin-bottom: 5px;
  text-align: left;
  display: flex;
  align-items: center; 
  cursor: pointer;
  /* padding: 15px 10px; */
  border-radius: 8px;
  transition: all 0.2s;
  position: relative;
}

.file-item:hover {
  background: #f0f7ff;
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.file-icon {
  width: 70px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  font-size: 40px;
}

.folder-icon { color: #ffb951; }
.file-icon-txt { color: #6ab0f3; }
.file-icon-img { color: #7dd856; }
.file-icon-pdf { color: #f96868; }
.file-icon-exe { color: #a678e0; }

.file-name {
  /* text-align: center; */
  display: flex;
  align-items: center;
  font-size: 14px;
  word-break: break-all;
  max-width: 100%;
}
.file-name img {
  margin-right: 5px;
}

.file-size {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
}
/* 上下文菜单 */
.context-menu {
  position: absolute;
  background: white;
  border: 1px solid #dce1e8;
  border-radius: 6px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 180px;
}

.menu-item {
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: all 0.2s;
}

.menu-item:hover {
  background: #f0f7ff;
}

.menu-divider {
  height: 1px;
  background: #dce1e8;
  margin: 5px 0;
}
/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
  
  .file-grid {
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
    gap: 15px;
  }
  
  .address-bar {
    flex-wrap: wrap;
  }
  
  .search-box {
    width: 100%;
    margin-top: 10px;
  }
}
</style> 